package com.thread;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

public class FairybattleThread implements Runnable {

	private Text text_main_show;
	private DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	private DateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
	private String cookie;
	private Document doc = null;
	private TableItem tit;
	private Table fairytable;
	private int listHaveChouse;
	private String bc;
	private Lock fairybattleLock = new ReentrantLock();

	@Override
	public void run() {
		fairybattleLock.lock();
		try {
			Display.getDefault().asyncExec(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					try {
						// TODO 自动生成的方法存根
						DocumentBuilder db = dbf.newDocumentBuilder();

						text_main_show.append("[" + df.format(new Date())
								+ "]:攻击" + tit.getText(3) + "→lv"
								+ tit.getText(1) + tit.getText(0) + "\n");
						URL urlLog = new URL(
								"http://117.121.6.138:10001/connect/app/exploration/fairybattle?serial_id="
										+ tit.getText(6) + "&user_id="
										+ tit.getText(5));
						HttpURLConnection connection = (HttpURLConnection) urlLog
								.openConnection();
						connection.setRequestMethod("POST");
						connection.addRequestProperty("Cookie", cookie);
						System.out.println("COOKIE="+cookie);
						InputStream is = connection.getInputStream();

						doc = db.parse(is);
						
						getTree(doc, 0);
						
						if (!doc.getElementsByTagName("code").item(0).getTextContent().equals("0")) {
							text_main_show.append("["
									+ df.format(new Date())
									+ "]:"
									+ doc.getElementsByTagName("message")
											.item(0).getTextContent() + "\n");
							if (0 < doc.getElementsByTagName("message").item(0)
									.getTextContent().indexOf("消灭")) {
								fairytable.remove(listHaveChouse);
							}
							return;
						}
						tit.setText(2, doc.getElementsByTagName("explore")
								.item(0).getChildNodes().item(2)
								.getChildNodes().item(4).getTextContent()
								+ "/"
								+ doc.getElementsByTagName("explore").item(0)
										.getChildNodes().item(2)
										.getChildNodes().item(5)
										.getTextContent());
						String escape_time_second = doc
								.getElementsByTagName("explore").item(0)
								.getChildNodes().item(2).getChildNodes()
								.item(6).getTextContent();
						int h = Integer.parseInt(escape_time_second) / 3600;
						int m = (Integer.parseInt(escape_time_second) % 3600) / 60;
						int s = Integer.parseInt(escape_time_second) % 60;
						String escape_time = h + ":" + m + ":" + s;
						tit.setText(4, escape_time);
						if (doc.getElementsByTagName("winner").item(0)
								.getTextContent().equals("0")) {
							text_main_show.append("["
									+ df.format(new Date())
									+ "]:战斗： BC:"
									+ bc
									+ "->"
									+ doc.getElementsByTagName("bc").item(0).getChildNodes().item(0)
											.getTextContent()
									+ " 经验"
									+ doc.getElementsByTagName("battle_result").item(0).getChildNodes()
											.item(3).getTextContent()
									+ "->"
									+ doc.getElementsByTagName("battle_result").item(0).getChildNodes()
										 	.item(4).getTextContent()
									+ " 收集道具："
									+ (Integer.parseInt(doc
											.getElementsByTagName(
													"special_item").item(0).getChildNodes().item(1)
											.getTextContent()) - Integer
											.parseInt(doc
													.getElementsByTagName(
															"special_item").item(0).getChildNodes()
													.item(0).getTextContent()))
									+ "->"
									+ doc.getElementsByTagName("special_item").item(0).getChildNodes()
											.item(1).getTextContent() + "\n");
							return;
						}
						text_main_show.append("["
								+ df.format(new Date())
								+ "]:战斗： BC:"
								+ bc
								+ "->"
								+ doc.getElementsByTagName("bc").item(0).getChildNodes().item(0)
										.getTextContent()
								+ " 经验"
								+ "--战斗胜利--"
								+ doc.getElementsByTagName("battle_result").item(0).getChildNodes()
										.item(3).getTextContent()
								+ "->"
								+ doc.getElementsByTagName("battle_result").item(0).getChildNodes()
										.item(4).getTextContent()
								+ " 收集道具："
								+ (Integer.parseInt(doc
										.getElementsByTagName("special_item").item(0).getChildNodes()
										.item(1).getTextContent()) - Integer
										.parseInt(doc
												.getElementsByTagName(
														"special_item").item(0).getChildNodes().item(0)
												.getTextContent()))
								+ "->"
								+ doc.getElementsByTagName("special_item").item(0).getChildNodes()
										.item(1).getTextContent() + "\n");
						// fairy_event=doc.getElementsByTagName("fairy_event");
						// remain_rewards=doc.getElementsByTagName("remaining_rewards").item(0).getTextContent();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			});
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			return;
		} finally {
			fairybattleLock.unlock();
		}

	}

	public FairybattleThread(Text text_main_show, String cookie, TableItem tit,
			Table fairytable, int listHaveChouse, String bc) {
		super();
		this.text_main_show = text_main_show;
		this.cookie = cookie;
		this.tit = tit;
		this.fairytable = fairytable;
		this.listHaveChouse = listHaveChouse;
		this.bc = bc;
	}

	public static void getTree(Node node, int times) {
		for (int i = 0; i < times; i++) {
			System.out.print("\t");
		}
		if (node.getNodeValue() != null) {
			System.out.print(node.getNodeValue() + "\n");
		} else {
			System.out.print(node.getNodeName() + "\n");
		}
		if (node.hasChildNodes()) {
			// System.out.print("\t"+node.getNodeName()+"\n");
			for (int i = 0; i < node.getChildNodes().getLength(); i++) {
				getTree(node.getChildNodes().item(i), times + 1);
			}
		} else {
			// System.out.print("\t"+node.getNodeName()+"\n");
		}
	}
}
